package org.chipu.shared.util.file;

import java.io.*;
import java.util.logging.Level;
import javax.annotation.Nonnull;
import org.chipu.shared.util.singletons.LoggingUtils;

public final class FileUtils {
	private FileUtils() {/**/}

	public static String getBaseName(@Nonnull File f) {
		int i = f.getName().lastIndexOf('.');
		if (i == -1)
			return f.getName();
		return f.getName().substring(0, i);
	}

	/** It does not return null, but empty string if there is no extension */
	public static String getExtension(@Nonnull File f) {
		int i = f.getName().lastIndexOf('.');
		if (i == -1)
			return "";
		return f.getName().substring(i + 1);
	}

	/**
	 * Equivalent to org.apache.commons.io.FileUtils#writeStringToFile(), plus a check that the file has been
	 * created successfully
	 */
	public static void createTextFile(@Nonnull File file, @Nonnull String text) throws IOException {
		File parentFile = file.getParentFile();
		// FIXME 5.2 sometimes the parentFile has no parent: when on tomcat, when on ant...
		if (parentFile == null)
			LoggingUtils.getLogger().severe("The file has no parent: " + file.getAbsolutePath());
		else
			parentFile.mkdirs();
		boolean b = file.createNewFile();
		if (!b && !file.exists())
			throw new IOException("Could not create file: " + file);
		setTextFile(file, text);
	}

	/** Equivalent to org.apache.commons.io.FileUtils#writeStringToFile() */
	public static void setTextFile(File file, String text) throws IOException {
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(file));
			writer.write(text);
			writer.flush();
		} finally {
			if (writer != null)
				try {
					writer.close();
				} catch(Exception ex) {
					ex.printStackTrace();
				}
		}
	}

	/** Equivalent to org.apache.commons.io.FileUtils#readFileToString() */
	public static String readTextFile(File file) throws IOException {
		if (file == null)
			return null;
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			char[] buffer = new char[2048];// CONFIGURABLE
			int count = 0;
			StringBuilder s = new StringBuilder();
			while(count != -1) {
				s.append(buffer, 0, count);
				count = reader.read(buffer);
			}
			// TEST performance bewteen readLine() and read(buffer)
			// String line = "";
			// String lineSeparator = System.getProperty("line.separator");
			// while((line = reader.readLine()) != null)
			// s.append(line).append(lineSeparator);
			return s.toString();
		} finally {
			if (reader != null)
				try {
					reader.close();
				} catch(IOException ex) {
					LoggingUtils.getLogger().log(Level.WARNING, "Error closing reader", ex);
				}
		}
	}
}